package novel.mzx.com.activity;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gyf.immersionbar.ImmersionBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import novel.mzx.com.R;
import novel.mzx.com.base.BaseActivity;
import novel.mzx.com.bean.BannerBean;
import novel.mzx.com.bean.ClassBean;
import novel.mzx.com.bean.CodeBean;
import novel.mzx.com.bean.SuccessBean;
import novel.mzx.com.http.Api;
import novel.mzx.com.utils.JSONUtils;
import novel.mzx.com.utils.PermissionsUtil;
import novel.mzx.com.utils.StringUtils;
import novel.mzx.com.utils.ToastUtils;
import novel.mzx.com.utils.Util;


/**
 * 注册页面
 */

public class RegiestActivity extends BaseActivity implements PermissionsUtil.IPermissionsCallback{

    @BindView(R.id.btn_login)
    Button btn_login;

    @BindView(R.id.et_phoneNum)
    EditText etPhoneNum;

    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.et_password2)
    EditText et_password2;

    @BindView(R.id.et_account)
    EditText et_account;

    @BindView(R.id.iv_logo)
    ImageView iv_logo;
    @BindView(R.id.tv_class)
    TextView tv_class;


    private PermissionsUtil permissionsUtil;


    @Override
    protected int getResourceId() {
        return R.layout.activity_regiest;
    }

    @Override
    protected void initView() {
        super.initView();
        ImmersionBar.with(this).titleBar(R.id.toolbar).keyboardEnable(true).init();
        ImmersionBar.with(RegiestActivity.this).keyboardEnable(false).statusBarDarkFont(true, 0.2f).navigationBarColor(R.color.btn3).init();


        getClassData();

        iv_logo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                permissionsUtil=  PermissionsUtil
                        .with(RegiestActivity.this)
                        .requestCode(1)
                        .isDebug(true)//开启log
                        .permissions(PermissionsUtil.Permission.Camera.CAMERA,PermissionsUtil.Permission.Storage.READ_EXTERNAL_STORAGE,PermissionsUtil.Permission.Storage.WRITE_EXTERNAL_STORAGE)
                        .request();
            }
        });
        tv_class.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Util.alertBottomWheelOption(RegiestActivity.this, lists, new Util.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int postion) {
                        tv_class.setText(lists.get(postion));
                    }
                });
            }
        });

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (StringUtils.getEditTextData(etPhoneNum).isEmpty() && StringUtils.getEditTextData(etPassword).isEmpty()){
                    ToastUtils.showToast(RegiestActivity.this,"请输入用户名或密码");
                    return;
                }
                if(StringUtils.getEditTextData(etPhoneNum).isEmpty()){
                    ToastUtils.showToast(RegiestActivity.this,"请输入用户名");
                    return;
                }

                if(StringUtils.getEditTextData(etPassword).isEmpty()){
                    ToastUtils.showToast(RegiestActivity.this,"请输入密码");
                    return;
                }

                if(StringUtils.getEditTextData(et_password2).isEmpty()){
                    ToastUtils.showToast(RegiestActivity.this,"请输入密码");
                    return;
                }

                if(!StringUtils.getEditTextData(etPassword).equals(StringUtils.getEditTextData(et_password2))){
                    ToastUtils.showToast(RegiestActivity.this,"两次输入的密码不一直");
                    return;
                }


                if(StringUtils.getEditTextData(et_account).isEmpty()){
                    ToastUtils.showToast(RegiestActivity.this,"请输入学号");
                    return;
                }

                if(path.equals("")){
                    ToastUtils.showToast(RegiestActivity.this,"请上传头像");
                    return;
                }


                String phone = StringUtils.getEditTextData(etPhoneNum);
                String pwd = StringUtils.getEditTextData(etPassword);
                String account = StringUtils.getEditTextData(et_account);


                OkGo.<String>post(Api.mainHost+ Api.photoUploadUrl)
                        .tag(this)
                        .params("file", new File(path))
                        .isMultipart(true)
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                Log.e("上传照片成功!",response.body());
                                SuccessBean getServiceImgBean = JSONUtils.parserObject(response.body(), SuccessBean.class);
                                if (getServiceImgBean.getResultCode() == 200){

                                    OkGo.<String>post(Api.mainHost+Api.regiestUrl)
                                            .params("userPwd",pwd)
                                            .params("userAccount",account)
                                            .params("userName",phone)
                                            .params("userRole",2)
                                            .params("userImg",getServiceImgBean.getData())
                                            .params("userNumber",account)
                                            .params("className",tv_class.getText().toString())
                                            .execute(new StringCallback() {
                                                @Override
                                                public void onSuccess(Response<String> response) {
                                                    Log.e("Registration",response.body());
                                                    CodeBean codeBean = JSONUtils.parserObject(response.body(),CodeBean.class);
                                                    int code = codeBean.getResultCode();
                                                    if(code == 200){
                                                        ToastUtils.showToast(RegiestActivity.this,"注册成功!");
                                                        finish();
                                                    }else {
                                                        ToastUtils.showToast(RegiestActivity.this,"注册失败!");
                                                    }
                                                }
                                            });
                                }
                            }
                        });


            }
        });
    }

    private ArrayList<String> lists = new ArrayList<>();
    private void getClassData() {
        OkGo.<String>get(Api.mainHost+Api.listClassInfoUrl)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("课程列表",response.body());

                        ClassBean bannerBean = JSONUtils.parserObject(response.body(),ClassBean.class);
                        int code = bannerBean.getResultCode();
                        if(code == 200){

                            List<ClassBean.Data> data = bannerBean.getData();
                            for (int i = 0; i < data.size(); i++) {
                                lists.add(data.get(i).getClassName());
                            }
                        }
                    }
                });
    }


    @Override
    public void onPermissionsGranted(int requestCode, String... permission) {
        dialogss();
    }

    @Override
    public void onPermissionsDenied(int requestCode, String... permission) {

    }

    Uri uritempFile;

    protected void cutImage(Uri uri) {
        if (uri == null) {
            Log.i("alanjet", "The uri is not exist.");
        }
        //getRealFilePath(this,tempUri);
        Intent intent = new Intent("com.android.camera.action.CROP");
        //com.android.camera.action.CROP这个action是用来裁剪图片用的
          /*  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            String url = getPath(this, uri);
            intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");
        }*/
        intent.setDataAndType(uri, "image/*");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        /**
         * 此方法返回的图片只能是小图片（sumsang测试为高宽160px的图片）
         * 故只保存图片Uri，调用时将Uri转换为Bitmap，此方法还可解决miui系统不能return data的问题
         */
        //intent.putExtra("return-data", true);

        //裁剪后的图片Uri路径，uritempFile为Uri类变量
        uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + System.currentTimeMillis()+"small.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, 3);
    }

    private AlertDialog.Builder builder;
    private void dialogss() {



        final String items[] = {"打开相机", "打开相册"};
        builder = new AlertDialog.Builder(this);  //先得到构造器
        //builder.setIcon(R.mipmap.ic_launcher);//设置图标，图片id即可
        builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //dialog.dismiss();
                //Toast.makeText(MActivity.this, items[which], Toast.LENGTH_SHORT).show();
                if (items[which].equals("打开相机")) {

                    testTakePhoto();
                } else if (items[which].equals("打开相册")) {
                    getAlbum();
                }
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    //打开相册
    private void getAlbum() {
        Intent getAlbumIntent = new Intent(Intent.ACTION_PICK);
        getAlbumIntent.setType("image/*");
        startActivityForResult(getAlbumIntent, 2);
    }


    private Uri fileUri1;
    File mPhotoFile;
    //打开系统相机
    private void testTakePhoto() {
        //指定相机拍照的存储路径
        mPhotoFile = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
        try {
            //判断文件是否存在，存在删除，不存在创建
            if (mPhotoFile.exists()){
                mPhotoFile.delete();
            }
            mPhotoFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //指定intent跳转到系统相机
        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        if(Build.VERSION.SDK_INT>=24){
            fileUri1= FileProvider.getUriForFile(RegiestActivity.this,"novel.mzx.com.provider",mPhotoFile);
            Log.e("获取到的url为",fileUri1.toString());
        }else {
            fileUri1 = Uri.fromFile(mPhotoFile);
        }


        //设置存储路径
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri1);
        try {
            //开启相机
            startActivityForResult(captureIntent, 5);
        } catch (Exception e) {
            Log.e("相机异常",e.getMessage());
            Toast.makeText(this, "跳转系统相机异常", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //需要调用onRequestPermissionsResult
        if(permissionsUtil != null){
            permissionsUtil.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    String path = "";
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(permissionsUtil != null){
            permissionsUtil.onActivityResult(requestCode, resultCode, data);
        }

        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 2) {
            if (resultCode == RESULT_OK) {//打开相册返回
                Uri albumUri = geturi(data);
                cutImage(albumUri);
            }
        }

        if (requestCode == 3) {
            if (resultCode == RESULT_OK) {
                try {
                    String absolutePath = new File(new URI(uritempFile.toString())).getAbsolutePath();
                    path = absolutePath;
                    Glide.with(RegiestActivity.this)
                            .load(path)
                            .asBitmap()
                            .placeholder(R.mipmap.ic_launcher)
                            .into(iv_logo);

                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            }
        }
        if (requestCode == 5) {
            if (resultCode == RESULT_OK) {//拍照返回

                cutImage(fileUri1);
            }
        }

    }

    public Uri geturi(Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr =getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }

}
